﻿using System;
using System.Text;

namespace H.PK
{
    /// <summary>
    /// 用于字符串加密的编码器
    /// </summary>
    internal class HEncoding : Encoding
    {
        /// <summary>
        /// 掩码,用于对字符串的byte数组进行加密
        /// </summary>
        public byte Mask { get; set; } = 0;



        public override int GetByteCount(char[] chars, int index, int count)
        {
            return UTF8.GetByteCount(chars, index, count);
        }

        public override int GetBytes(char[] chars, int charIndex, int charCount, byte[] bytes, int byteIndex)
        {
            int count = UTF8.GetBytes(chars, charIndex, charCount, bytes, byteIndex);
            for (int i = byteIndex, j = byteIndex + count; i < j; i++)
            {
                bytes[i] ^= Mask;
            }
            return count;
        }

        public override int GetCharCount(byte[] bytes, int index, int count)
        {
            byte[] xored = new byte[count];
            Array.Copy(bytes, index, xored, 0, count);
            for (int i = 0; i < count; i++)
            {
                xored[i] ^= Mask;
            }
            return UTF8.GetCharCount(xored, 0, count);
        }

        public override int GetChars(byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex)
        {
            byte[] xored = new byte[byteCount];
            Array.Copy(bytes, byteIndex, xored, 0, byteCount);
            for (int i = 0; i < byteCount; i++)
            {
                xored[i] ^= Mask;
            }
            return UTF8.GetChars(xored, 0, byteCount, chars, charIndex);
        }

        public override int GetMaxByteCount(int charCount)
        {
            return UTF8.GetMaxByteCount(charCount);
        }

        public override int GetMaxCharCount(int byteCount)
        {
            return UTF8.GetMaxCharCount(byteCount);
        }
    }
}
